package conf

import (
	"context"
	"database/sql"
	"fmt"
	"github.com/BurntSushi/toml"
	"github.com/caarlos0/env/v11"
	_ "github.com/go-sql-driver/mysql"
	"log"
	"os"
	"path"
	"sync"
	"time"
)

func LoadConfigFromFile(filePath string) error {
	//toml.DecodeFile()
	dir, _ := os.Getwd()
	pwd := path.Join(dir, filePath)
	_, err := toml.DecodeFile(pwd, &config)
	if err != nil {
		return err
	}
	return nil
}

func LoadConfigFromEnv() error {
	return env.Parse(config)
}

func LoadDB() *sql.DB {
	lock := sync.Mutex{}
	lock.Lock()
	defer lock.Unlock()
	if db == nil {
		dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4", config.MySQL.UserName, config.MySQL.Password, config.MySQL.Host, config.MySQL.Port, config.MySQL.Database)
		log.Println(dsn)
		sqlDB, err := sql.Open("mysql", dsn)
		if err != nil {
			panic(err)
		}
		for i := 0; i < 3; i++ {
			ctx, cancel := context.WithTimeout(context.Background(), time.Second)
			err = sqlDB.PingContext(ctx)
			cancel()
			if err == nil {
				break
			}
			log.Println("等待MySQL连接中s")
		}
		sqlDB.SetMaxOpenConns(config.MySQL.MaxOpenConn)
		sqlDB.SetMaxIdleConns(config.MySQL.MaxIdleConn)
		db = sqlDB
	}
	return db
}
